using AjaxControlToolkit;
using ASP;
using IPMS.AccessAuth;
using IPMS.BLL;
using Resources;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Threading;
using System.Web.Profile;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web;

public partial class Expenses : System.Web.UI.Page
{
    private decimal viewCountSum = 0M;
    protected void btnAddExpenditure_Click(object sender, EventArgs e)
    {
        Project runMethod = new Project();
        bool superUser = Convert.ToBoolean(this.Session["SuperUser"].ToString());
        runMethod.GetProjectStatus(base.Request.QueryString["pc"].ToString(), superUser, this.Session["OwnerGroupId"].ToString());
        if (runMethod.Status == "Expired")
        {
            this.lblError.Visible = true;
            this.lblError.Text = Messages.mProjectExpired.ToString();
        }
        else
        {
            Auth canAdd = new Auth(this.Session["UserId"].ToString(), string.Empty, "Finance");
            if (!canAdd.CanAdd())
            {
                this.lblError.Visible = true;
                this.lblError.Text = Messages.mNoAdd.ToString();
            }
            else
            {
                this.setButtons("new");
                this.clearText();
                this.setTextReadOnly(false);
                this.txtInvoiceNo.Enabled = true;
                this.cbForUpdate.Checked = false;
                this.txtInvoiceNo.Focus();
            }
        }
    }

    protected void btnCancelExpenditure_Click(object sender, EventArgs e)
    {
        this.clearText();
        this.setTextReadOnly(true);
        this.setButtons(string.Empty);
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        Project runMethod = new Project();
        bool superUser = Convert.ToBoolean(this.Session["SuperUser"].ToString());
        runMethod.GetProjectStatus(base.Request.QueryString["pc"].ToString(), superUser, this.Session["OwnerGroupId"].ToString());
        if (runMethod.Status == "Expired")
        {
            this.lblError.Visible = true;
            this.lblError.Text = Messages.mProjectExpired.ToString();
        }
        else
        {
            Auth canDelete = new Auth(this.Session["UserId"].ToString(), string.Empty, "Finance");
            if (!canDelete.CanDelete())
            {
                this.lblError.Visible = true;
                this.lblError.Text = Messages.mNoDelete.ToString();
            }
            else
            {
                try
                {
                    if (!string.IsNullOrEmpty(this.GridViewExpenditure.DataKeys[this.GridViewExpenditure.SelectedIndex].Value.ToString()))
                    {
                        this.ODSExpenditure.DeleteParameters["IsDelete"].DefaultValue = "true";
                        this.ODSExpenditure.DeleteParameters["DeleteBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                        this.ODSExpenditure.DeleteParameters["DeleteIP"].DefaultValue = HttpContext.Current.Request.UserHostAddress;
                        this.ODSExpenditure.DeleteParameters["Original_ProjectCode"].DefaultValue = base.Request.QueryString["pc"].ToString();
                        this.ODSExpenditure.DeleteParameters["Original_InvoiceNumber"].DefaultValue = this.GridViewExpenditure.DataKeys[this.GridViewExpenditure.SelectedIndex].Values["InvoiceNumber"].ToString();
                        this.ODSExpenditure.Delete();

                        this.setTextReadOnly(true);

                        setButtons("restore");

                        gvExpensesDeleteList.DataBind();
                    }
                }
                catch (ArgumentOutOfRangeException)
                {
                    this.lblError.Visible = true;
                    this.lblError.Text = Messages.mSelectRecordToDelete.ToString();
                }
            }
        }
    }

    protected void btnModifyExpenditure_Click(object sender, EventArgs e)
    {
        Project runMethod = new Project();
        bool superUser = Convert.ToBoolean(this.Session["SuperUser"].ToString());
        runMethod.GetProjectStatus(base.Request.QueryString["pc"].ToString(), superUser, this.Session["OwnerGroupId"].ToString());
        if (runMethod.Status == "Expired")
        {
            this.lblError.Visible = true;
            this.lblError.Text = Messages.mProjectExpired.ToString();
        }
        else
        {
            Auth canUpdate = new Auth(this.Session["UserId"].ToString(), string.Empty, "Finance");
            if (!canUpdate.CanUpdate())
            {
                this.lblError.Visible = true;
                this.lblError.Text = Messages.mNoEdit.ToString();
            }
            else
            {
                this.setButtons("modify");
                this.setTextReadOnly(false);
                this.txtInvoiceNo.ReadOnly = true;
                this.txtInvoiceNo.Enabled = false;
                this.txtReferenceDate.Focus();
            }
        }
    }

    protected void btnSaveExpenditure_Click(object sender, EventArgs e)
    {
        try
        {
            try
            {
                if (this.cbForUpdate.Checked)
                {
                    this.ODSExpenditure.UpdateMethod = "Update";
                    this.ODSExpenditure.UpdateParameters["ReferenceDate"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtReferenceDate.Text.ToString(), 1);
                    this.ODSExpenditure.UpdateParameters["ChargeFrom"].DefaultValue = this.txtChargeFrom.Text.ToString();
                    this.ODSExpenditure.UpdateParameters["Description"].DefaultValue = this.txtDescription.Text.ToString();
                    this.ODSExpenditure.UpdateParameters["ServiceCharge"].DefaultValue = this.txtServiceCharge.Text.ToString();
                    this.ODSExpenditure.UpdateParameters["UpdateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                    this.ODSExpenditure.UpdateParameters["Original_ProjectCode"].DefaultValue = base.Request.QueryString["pc"].ToString();
                    this.ODSExpenditure.UpdateParameters["Original_InvoiceNumber"].DefaultValue = this.txtInvoiceNo.Text.ToString();
                    this.ODSExpenditure.UpdateParameters["UpdateIP"].DefaultValue = HttpContext.Current.Request.UserHostAddress;
                    this.ODSExpenditure.Update();
                }
                else
                {
                    this.ODSExpenditure.InsertMethod = "Insert";
                    this.ODSExpenditure.InsertParameters["ProjectCode"].DefaultValue = base.Request.QueryString["pc"].ToString();
                    this.ODSExpenditure.InsertParameters["InvoiceNumber"].DefaultValue = this.txtInvoiceNo.Text.ToString();
                    this.ODSExpenditure.InsertParameters["ReferenceDate"].DefaultValue = IPDataFormat.ConvertDateFormat(this.txtReferenceDate.Text.ToString(), 1);
                    this.ODSExpenditure.InsertParameters["ChargeFrom"].DefaultValue = this.txtChargeFrom.Text.ToString();
                    this.ODSExpenditure.InsertParameters["Description"].DefaultValue = this.txtDescription.Text.ToString();
                    this.ODSExpenditure.InsertParameters["ServiceCharge"].DefaultValue = this.txtServiceCharge.Text.ToString();
                    this.ODSExpenditure.InsertParameters["CreateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                    this.ODSExpenditure.InsertParameters["UpdateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                    this.ODSExpenditure.InsertParameters["OwnerGroupID"].DefaultValue = this.Session["OwnerGroupID"].ToString();
                    this.ODSExpenditure.InsertParameters["CreateIP"].DefaultValue = HttpContext.Current.Request.UserHostAddress;
                    this.ODSExpenditure.Insert();
                    this.GridViewExpenditure.DataBind();
                    gvExpensesDeleteList.DataBind();
                }
            }
            catch (Exception ex)
            {
                List<string> lstValues = new List<string>();
                //this.lblError.Text = IPDataFormat.GenerateMessage(ex, lstValues);
                this.lblError.Text = ex.Message.ToString();
                this.chkForOperation.Checked = true;
            }
        }
        finally
        {
            //this.btnCancelExpenditure_Click(sender, e);
            setButtons(string.Empty);
            setTextReadOnly(true);
        }
    }

    private void clearText()
    {
        this.txtInvoiceNo.Text = string.Empty;
        this.txtReferenceDate.Text = string.Empty;
        this.txtChargeFrom.Text = string.Empty;
        this.txtDescription.Text = string.Empty;
        this.txtServiceCharge.Text = string.Empty;
        this.cbForUpdate.Checked = false;
        this.chkForOperation.Checked = false;
        this.lblError.Text = "";

        ViewState["invoiceno"] = null;
    }

    public void ComputeSum(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            decimal viewCount = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "ServiceCharge"));
            this.viewCountSum += viewCount;

            Label lblIsDelete = (Label)e.Row.FindControl("lblIsDelete");
            LinkButton lbtnRestore = (LinkButton)e.Row.FindControl("lbtnRestore");

            if (lblIsDelete != null && lbtnRestore != null)
            {
                if (Convert.ToBoolean(lblIsDelete.Text))
                {
                    lbtnRestore.Visible = true;
                }
                else
                {
                    lbtnRestore.Visible = false;
                }
            }

        }
        else if (e.Row.RowType == DataControlRowType.Footer)
        {
            HorizontalAlign alignRight = HorizontalAlign.Right;
            e.Row.Cells[5].Text = "Total: ";
            e.Row.Cells[5].HorizontalAlign = alignRight;
            e.Row.Cells[6].Text = string.Format("{0:C}", this.viewCountSum);
            e.Row.Cells[6].HorizontalAlign = alignRight;
        }
    }

    protected void GridViewExpenditure_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            string projectCode = base.Request.QueryString["pc"].ToString();
            string invoiceNo = this.GridViewExpenditure.DataKeys[this.GridViewExpenditure.SelectedIndex].Values["InvoiceNumber"].ToString();
            Finance runMethod = new Finance();
            runMethod.GetProjectExpenseInfo(projectCode, invoiceNo);
            this.txtInvoiceNo.Text = invoiceNo;
            this.txtReferenceDate.Text = IPDataFormat.FormatDateTime(runMethod.ReferenceDate);
            this.txtChargeFrom.Text = runMethod.ChargeFrom;
            this.txtDescription.Text = runMethod.Description;
            this.txtServiceCharge.Text = runMethod.ServiceCharge.ToString();
            this.chkForOperation.Checked = true;
            this.cbForUpdate.Checked = true;

            ViewState["invoiceno"] = invoiceNo;

            ViewState["isRestore"] = false;

            if (runMethod.IsDelete)
            {
                if (Session["SuperUser"] != null)
                {
                    if (Convert.ToBoolean(Session["SuperUser"]))
                    {
                        ViewState["isRestore"] = true;
                    }
                }
            }

            bool isRestore = Convert.ToBoolean(ViewState["isRestore"]);

            if (isRestore)
            {
                this.setButtons("restore");
                return;
            }
        }
        catch (NullReferenceException)
        {
        }
        this.setButtons(string.Empty);
    }

    protected void ibExpenditure_Click(object sender, ImageClickEventArgs e)
    {
        base.Response.Redirect("Expenses.aspx?pgi=" + this.txtProjectGroupID.Text.ToString() + "&type=" + this.txtType.Text.ToString() + "&pc=" + this.txtProjectCode.Text.ToString() + "&di=0&np=0");
    }

    protected void ibProjectHeaderInfo_Click(object sender, ImageClickEventArgs e)
    {
        base.Response.Redirect("HeaderInfo.aspx?pgi=" + this.txtProjectGroupID.Text.ToString() + "&type=" + this.txtType.Text.ToString() + "&pc=" + this.txtProjectCode.Text.ToString() + "&di=0&np=0");
    }

    protected void ibProjectInfo_Click(object sender, ImageClickEventArgs e)
    {
        base.Response.Redirect("ProjectInfo.aspx?pgi=" + this.txtProjectGroupID.Text.ToString() + "&type=" + this.txtType.Text.ToString() + "&pc=" + this.txtProjectCode.Text.ToString() + "&di=0&np=0");
    }

    protected void ibViewDoc_Click(object sender, ImageClickEventArgs e)
    {
        base.Response.Redirect("ProjectDocument.aspx?pgi=" + this.txtProjectGroupID.Text.ToString() + "&type=" + this.txtType.Text.ToString() + "&pc=" + this.txtProjectCode.Text.ToString() + "&di=0&np=0");
    }

    protected override void InitializeCulture()
    {
        string sCulture = ConfigurationManager.AppSettings["DefaultCulture"].ToString();
        try
        {
            sCulture = this.Session["Culture"].ToString();
        }
        catch (NullReferenceException)
        {
        }
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(sCulture);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(sCulture);
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Auth canView = new Auth(this.Session["UserId"].ToString(), string.Empty, "Finance");
        if (!canView.CanView())
        {
            base.Response.Redirect("ErrorPage/NotAllowedNoMaster.aspx");
        }
        else
        {
            this.setButtons(string.Empty);
            this.setTextReadOnly(true);
            if (!this.Page.IsPostBack)
            {
                string culture = this.Session["Culture"].ToString();
                this.txtProjectGroupID.Text = base.Request.QueryString["pgi"].ToString();
                this.txtProjectCode.Text = base.Request.QueryString["pc"].ToString();
                this.txtType.Text = base.Request.QueryString["type"].ToString();
                this.ibProjectInfo.ImageUrl = "~/Images/p_ProjInfo-" + culture + ".gif";
                this.ibViewDoc.ImageUrl = "~/Images/p_ViewDoc-" + culture + ".gif";
                this.ibProjectHeaderInfo.ImageUrl = "~/Images/p_AppProc-" + culture + ".gif";
                this.ibExpenditure.ImageUrl = "~/Images/p_Finance-" + culture + ".gif";
                this.btnDelete.Attributes.Add("onClick", "return confirm('" + Messages.DeleteConfirmation.ToString() + "')");
            }
        }

        if (Convert.ToBoolean(Session["SuperUser"]))
        {
            gvExpensesDeleteList.Visible = true;
        }
        else
        {
            gvExpensesDeleteList.Visible = false;
        }
    }

    protected void btnRestore_Click(object sender, EventArgs e)
    {
        Finance finance = new Finance();

        string updateBy = this.Page.User.Identity.Name.ToString();
        string updateIP = HttpContext.Current.Request.UserHostAddress;
        string projectCode = this.txtProjectCode.Text.ToString().Trim();
        string invoiceNumber = this.txtInvoiceNo.Text.Trim();

        bool isSuccess = finance.Update(false, updateBy, updateIP, projectCode, invoiceNumber);

        if (isSuccess)
        {
            GridViewExpenditure.DataBind();
            gvExpensesDeleteList.DataBind();
        }

    }

    private void setButtons(string action)
    {
        switch (action)
        {
            case "new":
                this.btnNew.Enabled = false;
                this.btnModify.Enabled = false;
                this.btnSave.Enabled = true;
                this.btnDelete.Enabled = false;
                this.btnDelete.Visible = true;
                this.btnRestore.Visible = false;
                this.chkForOperation.Checked = true;
                return;

            case "modify":
                this.btnNew.Enabled = false;
                this.btnModify.Enabled = false;
                this.btnSave.Enabled = true;
                this.btnDelete.Enabled = false;
                this.btnDelete.Visible = true;
                this.btnRestore.Visible = false;
                this.chkForOperation.Checked = true;
                return;

            case "save":
                this.btnNew.Enabled = true;
                this.btnModify.Enabled = false;
                this.btnSave.Enabled = false;
                this.btnDelete.Visible = true;
                this.btnRestore.Visible = false;
                this.btnDelete.Enabled = false;
                return;

            case "restore":
                this.btnNew.Enabled = false;
                this.btnModify.Enabled = false;
                this.btnSave.Enabled = false;
                this.btnDelete.Visible = false;
                this.btnRestore.Visible = true;
                return;
        }
        this.btnNew.Enabled = true;
        this.btnModify.Enabled = ViewState["invoiceno"] != null;
        this.btnSave.Enabled = false;
        this.btnDelete.Enabled = ViewState["invoiceno"] != null;
        this.btnRestore.Visible = false;
        this.btnDelete.Visible = true;
    }

    private void setTextReadOnly(bool bBool)
    {
        this.txtInvoiceNo.ReadOnly = bBool;
        this.txtReferenceDate.ReadOnly = bBool;
        this.txtReferenceDate.Enabled = !bBool;
        this.txtChargeFrom.ReadOnly = bBool;
        this.txtDescription.ReadOnly = bBool;
        this.txtServiceCharge.ReadOnly = bBool;
        this.txtServiceCharge.Enabled = !bBool;
    }
    protected void GridViewExpenditure_RowCommand(object sender, GridViewCommandEventArgs e)
    {

    }

    protected void gvExpensesDeleteList_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void gvExpensesDeleteList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Restore")
        {
            GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
            int index = row.RowIndex;

            string projectCode = this.gvExpensesDeleteList.DataKeys[index].Values["ProjectCode"].ToString().Trim();
            string invoiceNumber = this.gvExpensesDeleteList.DataKeys[index].Values["InvoiceNumber"].ToString().Trim();
            string isDelete = this.gvExpensesDeleteList.DataKeys[index].Values["IsDelete"].ToString().Trim();

            if (this.Session["SuperUser"] != null)
            {
                if (Convert.ToBoolean(isDelete) && Convert.ToBoolean(this.Session["SuperUser"]))
                {
                    Finance finance = new Finance();

                    string updateBy = this.Page.User.Identity.Name.ToString();
                    string updateIP = HttpContext.Current.Request.UserHostAddress;

                    bool isSuccess = finance.Update(false, updateBy, updateIP, projectCode, invoiceNumber);

                    if (isSuccess)
                    {
                        this.GridViewExpenditure.DataBind();
                        this.gvExpensesDeleteList.DataBind();
                    }
                }
            }
        }
        else if (e.CommandName == "ForceDelete")
        {
            GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
            int index = row.RowIndex;

            string projectCode = this.gvExpensesDeleteList.DataKeys[index].Values["ProjectCode"].ToString().Trim();
            string invoiceNumber = this.gvExpensesDeleteList.DataKeys[index].Values["InvoiceNumber"].ToString().Trim();
            string isDelete = this.gvExpensesDeleteList.DataKeys[index].Values["IsDelete"].ToString().Trim();

            if (this.Session["SuperUser"] != null)
            {
                if (Convert.ToBoolean(isDelete) && Convert.ToBoolean(this.Session["SuperUser"]))
                {
                    Finance finance = new Finance();

                    bool isSuccess = finance.Delete(projectCode, invoiceNumber);

                    if (isSuccess)
                    {
                        this.gvExpensesDeleteList.DataBind();
                    }
                }
            }
        }
    }

    protected void gvExpensesDeleteList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            decimal viewCount = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "ServiceCharge"));
            this.viewCountSum += viewCount;

            LinkButton lbtnFroceDelete = (LinkButton)e.Row.FindControl("lbtnFroceDelete");

            if (lbtnFroceDelete != null)
            {
                lbtnFroceDelete.Attributes.Add("onClick", "return confirm('" + Messages.DeleteConfirmation.ToString() + "')");
            }

            LinkButton lbtnRestore = (LinkButton)e.Row.FindControl("lbtnRestore");
            if (lbtnRestore != null)
            {
                lbtnRestore.Attributes.Add("onClick", "return confirm('" + Messages.RestoreConfirmation.ToString() + "')");
            }
        }
        else if (e.Row.RowType == DataControlRowType.Footer)
        {
            HorizontalAlign alignRight = HorizontalAlign.Right;
            e.Row.Cells[5].Text = "Total: ";
            e.Row.Cells[5].HorizontalAlign = alignRight;
            e.Row.Cells[6].Text = string.Format("{0:C}", this.viewCountSum);
            e.Row.Cells[6].HorizontalAlign = alignRight;
        }
    }
}
